﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using iLangl.Model;

namespace iLangl.LanguageWire.DAL.iLanglDAL.XMLStorage
{
	public class ContactDAL: BaseStorageDAL, IContactDAL
	{
		public void CreateContact(Contact contact, IDbTransaction transaction)
		{
			dtoXMLStorage.ContactRow contactRow = Storage.Contact.FindById(contact.Id);

			bool isNew = (contactRow == null);

			if (isNew)
			{
				contactRow = Storage.Contact.NewContactRow();
			}
				
			contactRow.CompanyId = contact.Company.Id;
			contactRow.EMail = contact.Email;
			contactRow.FirstName = contact.FirstName;
			contactRow.Id = contact.Id;
			contactRow.LastName = contact.LastName;
			contactRow.Phone = contact.Phone;
			contactRow.Title = contact.Title;
			contactRow.TPIdentity = contact.TPIdentity;

			if (isNew)
			{
				Storage.Contact.AddContactRow(contactRow);
				contactRow.TimeSpan = CurrentTimeSpan;
				UpdateDeliveryTime(eEntityType.Contact, contact.Id, contactRow.TimeSpan);
			}

			if (transaction == null)
			{
				AcceptChanges();
			}
		}



		public void UpdateContactReference(string ilanglCustomerId, int customerId, IDbTransaction transaction)
		{
			dtoXMLStorage.ContactRow cr = Storage.Contact.FindById(ilanglCustomerId);

			if (cr == null)
				return;

			cr.TPIdentity= customerId.ToString();
			cr.TimeSpan = CurrentTimeSpan;

			if (transaction == null)
			{
				AcceptChanges();
			}

		}


		public Contact ReadContact(string contactId)
		{
			dtoXMLStorage.ContactRow contactRow = Storage.Contact.FindById(contactId);

			if (contactRow == null)
				return null;

			Contact contact = new Contact();

			contact.Id = contactRow.Id;

			if (!contactRow.IsEMailNull())
				contact.Email = contactRow.EMail;

			if (!contactRow.IsFirstNameNull())
				contact.FirstName = contactRow.FirstName;


			if (!contactRow.IsLastNameNull())
				contact.LastName = contactRow.LastName;

			if (!contactRow.IsPhoneNull())
				contact.Phone = contactRow.Phone;

			if (!contactRow.IsTitleNull())
				contact.Title = contactRow.Title;


			if (!contactRow.IsTPIdentityNull())
				contact.TPIdentity = contactRow.TPIdentity;

			contact.Company = new Company();
			contact.Company.Id = contactRow.CompanyId;

			return contact;

		}


		public Contact ReadContactByTPIdentity(string TPIndentity)
		{
			if(String.IsNullOrEmpty(TPIndentity))
				return null;

			foreach (dtoXMLStorage.ContactRow cr in Storage.Contact)
			{
				if(cr.IsTPIdentityNull())
					continue;

				if (String.Compare(cr.TPIdentity.Trim(), TPIndentity.Trim(), true) == 0)
				{
					return ReadContact(cr.Id);
				}
			}

			return null;
		}

		#region IContactDAL Members


		public void UpdateContact(Contact contact, IDbTransaction transaction)
		{
			CreateContact(contact, transaction);
		}

		#endregion
	}
}
